package com.bestdo.returndata;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;

public class ClientByte {
	
	public static String sep = "|";
	public static int sepb = sep.getBytes()[0];
	public static void main(String[] args) {
		args = new String[]{"127.0.0.1","8088","就这样不"};
		
		if(args == null || args.length !=3){
			System.err.println("***请输入正确的ip port data参数！***");
			System.exit(0);
		}
		String ip = args[0];
		int port = Integer.parseInt(args[1]);
		String data = args[2];
		
		try( Socket s = new Socket(ip, port);
			 InputStream is = s.getInputStream();
			 OutputStream os = s.getOutputStream()
			){
			os.write(deal(data.getBytes()));
			os.flush();
			
			System.out.println("***客户端发送："+data);
			 
			System.out.println("***服务端返回："+new String(read(is)));
			
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("***服务失败！***");
			System.exit(0);
		}
		
	}
	
	public static byte[] deal(byte[] by){
		byte[] len = (String.valueOf(by.length)+sep).getBytes();
		byte[] b =  Arrays.copyOf(len, len.length+by.length);
		System.arraycopy(by, 0, b, len.length, by.length);
		return b;
	}
	
	public static byte[] read(InputStream is) throws IOException{
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
	    do{
	    	int b = is.read();
	    	if(sepb == b || b==-1){
	    		break;
	    	}
	    	bo.write(b);
	    }while(true);
		int len = Integer.parseInt(new String(bo.toByteArray()));
		byte[] temp = new byte[512];
		int tl = 0;
		int i = 0;
		bo.reset();
		do {
			i = is.read(temp);
			if(i == -1){
				break;
			}
			bo.write(temp, 0, i);
			tl += i;
			if(tl >= len){
				break;
			}
		} while (true);
		
		return bo.toByteArray();
	}
}
